<template>
  <el-menu v-if="visible" class="context-menu" :style="style">
    <el-menu-item
      v-for="item in menuItems"
      :key="item.index"
      :index="'' + item.index"
      @click="handleMenuClick(item)"
    >
      {{ item.label }}
    </el-menu-item>
  </el-menu>
</template>

<script>
export default {
  name: "ContextMenu",

  data() {
    return {
      visible: false,
      style: {
        top: 100 + "px",
        left: 100 + "px",
      },
      menuItems: [],
    };
  },

  watch: {
    // visible: {
    //   handler(value) {
    //     if (value) {
    //       this.$nextTick(() => {
    //         console.log("sss");
    //         window.addEventListener("click", this.handleWindowClick);
    //       });
    //     } else {
    //       window.removeEventListener("click", this.handleWindowClick);
    //     }
    //   },
    //   flush: "post",
    // },
  },

  methods: {
    open(event, menuItems) {
      this.visible = true;
      this.style = {
        top: event.clientY + "px",
        left: event.clientX + "px",
      };
      this.menuItems = menuItems;
    },

    close() {
      this.visible = false;
    },

    handleMenuClick(data) {
      console.log("item", data);
      data.action();

      // 关闭
      this.close();
    },

    handleClick(key) {
      console.log("handleClick", key);
    },

    handleWindowClick() {
      console.log("this.visible", this.visible);
      this.close();
    },
  },
};
</script>

<style scoped>
.context-menu {
  width: 160px;
  position: fixed;
  top: 0;
  left: 0;
  border: none;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  background-color: #ffffff;
}
.el-menu-item {
  height: 36px !important;
}
</style>
